//
//  CJRewardVideoGMAdapter.m
//  CJModileGMAdapter
//
//  Created by shanghailingye on 2024/4/24.
//

#import "CJRewardVideoToBidAdapter.h"

@interface CJRewardVideoToBidAdapter()<CJRewardVideoAdDelegate>

@property (nonatomic, weak) id<AWMCustomRewardedVideoAdapterBridge> bridge;
@property (nonatomic, strong) CJRewardVideoAd *rewardVideo;
@property (nonatomic, copy) NSString *userId;
// 是否是bidding
@property (nonatomic, assign) BOOL isBidding;

@end

@implementation CJRewardVideoToBidAdapter

- (instancetype)initWithBridge:(id<AWMCustomRewardedVideoAdapterBridge>)bridge {
    self = [super init];
    if (self) {
        _bridge = bridge;
    }
    return self;
}
- (BOOL)mediatedAdStatus {
    return YES;
}

- (void)loadAdWithPlacementId:(NSString *)placementId parameter:(AWMParameter *)parameter {
    _isBidding = parameter.isHeaderBidding;
    WindMillAdRequest *request = [self.bridge adRequest];
    _userId = request.userId;
    self.rewardVideo = [[CJRewardVideoAd alloc] initWithResourceId:placementId userId:request.userId extend:@""];
    self.rewardVideo.delegate = self;
    [self.rewardVideo loadAdData];
}

- (BOOL)showAdFromRootViewController:(UIViewController *)viewController parameter:(AWMParameter *)parameter {
    [self.rewardVideo showFromRootViewController:viewController];
    return true;
}

- (void)destory {
    self.rewardVideo = nil;
}

- (void)didReceiveBidResult:(AWMMediaBidResult *)result {
    NSLog(@"%@", result.win ? @"胜出" : @"竞胜失败");
}

#pragma mark CJRewardVideoAdDelegate
- (void)rewardVideoOnRewarded:(CJRewardVideoAd *)rewardAd requestId:(NSString *)requestId {
    WindMillRewardInfo *info = [WindMillRewardInfo new];
    info.isCompeltedView = true;
    info.userId = _userId;
    [self.bridge rewardedVideoAd:self didRewardSuccessWithInfo:info];
}

- (void)rewardVideoAdDidLoad:(CJRewardVideoAd *)rewardAd resourceId:(NSString *)resourceId {
    NSInteger cpm = [self.rewardVideo getECpm];
    NSDictionary *ext = @{
        AWMMediaAdLoadingExtECPM : cpm ? [NSString stringWithFormat:@"%ld", cpm] : @"0",
    };
    if (_isBidding) { [self.bridge rewardedVideoAd:self didAdServerResponseWithExt:ext]; }
    [self.bridge rewardedVideoAdDidLoad:self];
}

- (void)rewardVideoAdOnShow:(CJRewardVideoAd *)rewardAd {
    [self.bridge rewardedVideoAdDidVisible:self];
}

- (void)rewardVideoAdLoadFailed:(CJRewardVideoAd *)rewardAd error:(NSError *)error {
    [self.bridge rewardedVideoAdDidShowFailed:self error:error];
}

- (void)rewardVideoAdOnClicked:(CJRewardVideoAd *)rewardAd {
    [self.bridge rewardedVideoAdDidClick:self];
}

- (void)rewardVideoAdOnClosed:(CJRewardVideoAd *)rewardAd {
    [self.bridge rewardedVideoAdDidClose:self];
}

@end
